package org.example.ruangong.service.impl;

import org.example.ruangong.model.User;
import org.example.ruangong.service.UserService;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class UserServiceImpl implements UserService {

    // 模拟数据库存储用户信息
    private static Map<String, User> userDatabase = new ConcurrentHashMap<>();

    @Override
    public boolean addUser(User user) {
        if (userDatabase.containsKey(user.getEmail())) {
            return false; // 用户已存在
        }

        // 设置用户ID
        user.setUid(userDatabase.size() + 1);
        userDatabase.put(user.getEmail(), user);
        return true;
    }

    @Override
    public boolean deleteUser(int uid) {
        Iterator<Map.Entry<String, User>> iterator = userDatabase.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, User> entry = iterator.next();
            if (entry.getValue().getUid() == uid) {
                iterator.remove();
                return true;
            }
        }
        return false;
    }

    @Override
    public User getUserByEmail(String email) {
        return userDatabase.get(email);
    }

    @Override
    public User getUserById(int uid) {
        for (User user : userDatabase.values()) {
            if (user.getUid() == uid) {
                return user;
            }
        }
        return null;
    }

    @Override
    public boolean verifyPassword(String email, String password) {
        User user = userDatabase.get(email);
        return user != null && user.getPassword().equals(password);
    }

    @Override
    public boolean updatePassword(String email, String oldPassword, String newPassword) {
        User user = userDatabase.get(email);
        if (user != null && user.getPassword().equals(oldPassword)) {
            user.setPassword(newPassword);
            userDatabase.put(email, user);
            return true;
        }
        return false;
    }

    @Override
    public boolean updatePassword(String email, String newPassword) {
        User user = userDatabase.get(email);
        if (user != null) {
            user.setPassword(newPassword);
            userDatabase.put(email, user);
            return true;
        }
        return false;
    }
}
